//
//  LastSongViewController.m
//  YiQiTingShu
//
//  Created by dllo on 15/11/11.
//  Copyright © 2015年 直到世界的尽头. All rights reserved.
//

#import "LastSongViewController.h"
#import "PublicHeader.h"
#import "WHNView.h"
#import "AFTools.h"
#import "WWTableContentModel.h"
#import "FAlbumDetail.h"
#import "WWContentTableCell.h"
#import <MJExtension.h>
#import <UIImageView+WebCache.h>
#import "PlayerButton.h"
#import "UIImage+GaussianBlur.h"
#import "PlayerButton.h"
#import "Music.h"
#import "WHNPlayListViewController.h"

#define URLString @"http://mobile.ximalaya.com/mobile/track/playpage/%@?albumId=%@&device=iPhone&trackUid=%@"
#define ListString @"http://mobile.ximalaya.com/mobile/playlist/album?albumId=%@&device=iPhone"

@interface LastSongViewController ()<WHNViewDelegate>
@property(nonatomic, strong)NSMutableArray *dataSource;
@property(nonatomic, strong)WHNView *headerView;
@property(nonatomic, strong)FAlbumDetail *detail;
@property (nonatomic, strong)NSMutableArray *mp3Array;
@property (nonatomic, assign)NSInteger count;
@property (weak ,nonatomic) NSTimer *timer;
@end

@implementation LastSongViewController

#pragma mark 定时器
-(NSTimer *)timer{
    if (!_timer) {
        _timer=[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateProgress) userInfo:nil repeats:true];
    }
    return _timer;
}

-(void)viewWillAppear:(BOOL)animated
{
    self.headerView.WHNPlayButton.selected = ![[NSUserDefaults standardUserDefaults] objectForKey:@"button"];
    
    [PlayerButton shareButton].hidden = YES;
    
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBar.barTintColor = [UIColor clearColor];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"fy_backView"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
}

-(void)viewWillDisappear:(BOOL)animated
{
    self.headerView.WHNPlayButton.selected = ![[NSUserDefaults standardUserDefaults] objectForKey:@"button"];
    
    [PlayerButton shareButton].hidden = NO;
    
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"fy_backWhiteView"] forBarMetrics:UIBarMetricsDefault];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view NightWithType:UIViewColorTypeNormal];
    
    if (_albumId) {
        [self initData];
    }
    else{
        [self initData1];
    }
    
    [self.view addSubview:[[UIView alloc] initWithFrame:CGRectMake(0, 0, FitConstant_XorWidth(1), FitConstant_YorHeight(1))]];
    
    _headerView = [[WHNView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, FitConstant_YorHeight(510))];
    _headerView.delegate = self;
    _headerView.kind = WHNViewKindPictureTopList;
    [self.view addSubview:_headerView];
    [[NSUserDefaults standardUserDefaults] setObject:_trackID forKey:@"trackID"];
    [[NSUserDefaults standardUserDefaults] setObject:_trackUid forKey:@"trackUid"];
    [[NSUserDefaults standardUserDefaults] setObject:_albumId forKey:@"albumId"];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
    button.frame = FitRectMake(20, 20, 40, 40);
    [button setImage:[UIImage imageNamed:@"iconfont-ananzuiconv265"] forState:UIControlStateNormal];
    [self.view addSubview:button];
    
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(buttonAction)];
    swipe.direction = UISwipeGestureRecognizerDirectionDown;
    [self.view addGestureRecognizer:swipe];
}

-(void)buttonAction
{
    [self.view removeFromSuperview];
}

#pragma mark - 初始化数据(传入参数没有albumID时)
-(void)initData1
{
    _dataSource = [NSMutableArray array];
    self.mp3Array = [NSMutableArray array];
    //播放信息
    //NSLog(@"%@", [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/track/detail?device=iPhone&trackId=%@", _trackID]);
    [AFTools getDataByURLString:[NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/track/detail?device=iPhone&trackId=%@", _trackID] WithDataBlock:^(id data) {
        //设置播放歌曲
        for (NSString *str in data) {
            if ([str isEqualToString:@"playUrl64"]) {
                [self.mp3Array addObject:[data objectForKey:str]];
            }
        }
        [PlayerButton shareButton].imageURL = [data objectForKey:@"coverMiddle"];
        //设置播放图片
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:FitRectMake(10, 10, 10, 10)];
        [imageView sd_setImageWithURL:[NSURL URLWithString:[data objectForKey:@"coverMiddle"]] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            [[PlayerButton shareButton] setImage:imageView.image forState:UIControlStateNormal];
        }];
        _albumId = [data objectForKey:@"albumId"];
        //获取列表信息
        [AFTools getDataByURLString:[NSString stringWithFormat:URLString, _trackID, _albumId, _trackUid] WithDataBlock:^(id data) {
            //专辑数组
            NSArray *array = [WWTableContentModel mj_objectArrayWithKeyValuesArray:[data objectForKey:@"associationAlbumsInfo"]];
            //简介信息
            _detail = [FAlbumDetail mj_objectWithKeyValues:[data objectForKey:@"albumInfo"]];
            [_dataSource addObjectsFromArray:array];
            
            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:_detail.coverLarge]]];
            if (!image) {
                image = [UIImage imageNamed:@"placeholderZh"];
            }
            _headerView.WHNBackImageView.image = [UIImage blurryImage:image withBlurLevel:0.4];
            [_headerView.WHNCenterImageView sd_setImageWithURL:[NSURL URLWithString:_detail.coverLarge] placeholderImage:[UIImage imageNamed:@"placeholderZh"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            }];
            if (self.mp3Array.count) {
                [PlayerButton shareButton].isPlay = YES;
                [[Music shareInstance] playMusicWith:self.mp3Array[0]];
                [[Music shareInstance].myPlayer play];
                [self.timer setFireDate:[NSDate distantPast]];
            }
        }];
    }];
}

-(void)initData
{
    _dataSource = [NSMutableArray array];
    self.mp3Array = [NSMutableArray array];
    //播放信息
    [AFTools getDataByURLString:[NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/track/detail?device=iPhone&trackId=%@", _trackID] WithDataBlock:^(id data) {
        //设置播放歌曲
        for (NSString *str in data) {
            if ([str isEqualToString:@"playUrl64"]) {
                [self.mp3Array addObject:[data objectForKey:str]];
            }
        }
        [PlayerButton shareButton].imageURL = [data objectForKey:@"coverMiddle"];
        //设置播放图片
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:FitRectMake(FitConstant_XorWidth(10), FitConstant_YorHeight(10), FitConstant_XorWidth(10), FitConstant_YorHeight(10))];
        [[NSUserDefaults standardUserDefaults] setObject:[data objectForKey:@"coverMiddle"] forKey:@"picURL"];
        [imageView sd_setImageWithURL:[NSURL URLWithString:[data objectForKey:@"coverMiddle"]] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            [[PlayerButton shareButton] setImage:imageView.image forState:UIControlStateNormal];
            
        }];
    }];
    //获取列表信息
    [AFTools getDataByURLString:[NSString stringWithFormat:URLString, _trackID, _albumId, _trackUid] WithDataBlock:^(id data) {
        //专辑数组
        NSArray *array = [WWTableContentModel mj_objectArrayWithKeyValuesArray:[data objectForKey:@"associationAlbumsInfo"]];
        //简介信息
        _detail = [FAlbumDetail mj_objectWithKeyValues:[data objectForKey:@"albumInfo"]];
        [_dataSource addObjectsFromArray:array];
        
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:_detail.coverLarge]]];
        if (!image) {
            image = [UIImage imageNamed:@"placeholderZh"];
        }
        _headerView.WHNBackImageView.image = [UIImage blurryImage:image withBlurLevel:0.4];
        [_headerView.WHNCenterImageView sd_setImageWithURL:[NSURL URLWithString:_detail.coverLarge] placeholderImage:[UIImage imageNamed:@"placeholderZh"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        }];
        [_headerView.WHNListButton addTarget:self action:@selector(playListAction) forControlEvents:UIControlEventTouchUpInside];
        if (self.mp3Array.count) {
            [PlayerButton shareButton].isPlay = YES;
            [[Music shareInstance] playMusicWith:self.mp3Array[0]];
            [[Music shareInstance].myPlayer play];
            [self.timer setFireDate:[NSDate distantPast]];
        }
    }];
}

- (void)passValue:(BOOL)isPlay {
    if (isPlay) {
        [[Music shareInstance].myPlayer play];
        [self.timer setFireDate:[NSDate distantPast]];
    } else {
        [[Music shareInstance].myPlayer pause];
        [self.timer setFireDate:[NSDate distantFuture]];
    }
    [PlayerButton shareButton].isPlay = isPlay;
}
#pragma mark 播放列表点击方法
-(void)playListAction
{
    WHNPlayListViewController *listVC = [[WHNPlayListViewController alloc]init];
    listVC.albumId = _albumId;
    listVC.myBlock = ^(NSString *trackId, NSString *uid, NSString *title){
        _trackID = trackId;
        _trackUid = uid;
        self.title = title;
        [self initData];
    };
    [self.navigationController pushViewController:listVC animated:YES];
}

#pragma mark - 进度条
-(void)updateProgress{
    CGFloat currentTime = CMTimeGetSeconds([Music shareInstance].myPlayer.currentTime);
    CGFloat allTime = CMTimeGetSeconds([Music shareInstance].myPlayer.currentItem.duration);
    [_headerView.WHNSlider setProgress:currentTime / allTime];
}


@end
